import { NestFactory } from '@nestjs/core'
import { AppModule } from './app.module'
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'
import { ValidationPipe } from '@nestjs/common'
import config from './config'
import banner from './banner'

async function bootstrap() {
  const app = await NestFactory.create(AppModule)

  // 设置全局路由前缀
  app.setGlobalPrefix('api')

  // 启用 CORS，允许所有来源跨域请求
  app.enableCors()

  // 全局验证管道
  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
      whitelist: true,
      // forbidNonWhitelisted: true,
    }),
  )

  // Swagger 配置
  const swaggerConfig = new DocumentBuilder()
    .setTitle('VeloAdmin API')
    .setDescription('VeloAdmin 后端接口文档')
    .setVersion('1.0')
    .build()
  const document = SwaggerModule.createDocument(app, swaggerConfig)
  SwaggerModule.setup('api-docs', app, document)

  await app.listen(config.port)
  console.log(`\r\n\x1b[32m----------------------------------------------------------------------------\x1b[0m`)
  console.log(`\r\n\x1b[32mVeloAdmin 服务器启动成功！\x1b[0m\r\n`)
  console.log(`\x1b[34m端口 \x1b[33m${config.port}\x1b[0m`)
  console.log(`\x1b[34m接口文档地址：\x1b[0m \x1b[36mhttp://localhost:${config.port}/api-docs\x1b[0m`)
  console.log(`\x1b[34m数据库地址：\x1b[0m \x1b[33m${config.database.host}:${config.database.port}\x1b[0m`)
  console.log(`\x1b[34m数据库名称：\x1b[0m \x1b[33m${config.database.database}\x1b[0m`)
  console.log(`\x1b[34m当前环境：\x1b[0m \x1b[33m${process.env.NODE_ENV}\x1b[0m\r\n`)
  console.log(`\r\n\x1b[32m${banner}\x1b[0m\r\n`)
  console.log(`\x1b[32m----------------------------------------------------------------------------\x1b[0m`)
}

bootstrap().catch((error) => {
  console.error('启动应用时发生错误:', error)
  process.exit(1)
})
